package com.hmdp.thread;


/**
 * 雪花算法ID生成器
 */
public class SnowflakeIdGenerator {
    private final long datacenterId; // 数据中心ID
    private final long machineId;    // 机器ID
    private long sequence = 0L;      // 序列号
    private long lastTimestamp = -1L; // 上次时间戳

    private static final long START_STMP = 1480166465631L; // 起始时间戳(2016-11-26)
    private static final long DATACENTER_BIT = 5L;         // 数据中心位数
    private static final long MACHINE_BIT = 5L;            // 机器标识位数
    private static final long SEQUENCE_BIT = 12L;          // 序列号位数

    private static final long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
    private static final long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);

    private static final long MACHINE_LEFT = SEQUENCE_BIT;
    private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private static final long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    public SnowflakeIdGenerator(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    public synchronized long nextId() {
        long currTimestamp = getNewTimestamp();
        if (currTimestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }

        if (currTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0L) {
                currTimestamp = getNextTimestamp();
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = currTimestamp;

        return (currTimestamp - START_STMP) << TIMESTMP_LEFT
                | datacenterId << DATACENTER_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }

    private long getNextTimestamp() {
        long timestamp = getNewTimestamp();
        while (timestamp <= lastTimestamp) {
            timestamp = getNewTimestamp();
        }
        return timestamp;
    }

    private long getNewTimestamp() {
        return System.currentTimeMillis();
    }
}